<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\common\model\User as UserModel;
use app\common\model\Area;
use think\App;
use think\facade\View;
use think\response\Json;
use app\common\model\Level;
use app\common\model\Assets;
use app\common\model\Logs;
use app\common\builder\TableFront;
use app\common\builder\TableBuilder;
use think\exception\ValidateException;

class User extends Base
{
    //主键，默认为id
    protected $pk = 'id';

    //验证器
    protected $validate = 'User';

    //主模型
    protected $model = '\app\common\model\User';

    //额外查询条件
    protected $extraSearch = ['is_active', 'is_service'];

    //关联模型
    protected $hasOne = ['level', 'assets', 'contract', 'flag', 'bonus'];

    protected $append = ['contract_role', 'child_count', 'exp_time', 'down_time','is_bonus', 'agent_level_text', 'bonus_reach', 'exp_leader_time_text'];

    //普通会员
    public function ordinary()
    {
        return $this->setTable('ordinary', ['delete'], ['add' => ['width' => 1000, 'height' => 1000]], ['level_id' => 1]);
    }

    //正式会员
    public function formal()
    {
        return $this->setTable('formal', '', '', ['level_id' => ['>', 1]], 2);
    }

    //实名会员
    public function real()
    {
        return $this->setTable('ordinary', '', '', ['real_status' => 1], 1);
    }

    public function setTable($action, $rb = [], $tb = [], $extra_map = [], $active = 1)
    {
        //构建table
        $tableFront = TableFront::getInstance()
            ->addRow(['type' => 'checkbox', 'fixed' => 'left', 'title' => '全选'])
            ->addRow(['field' => 'id', 'sort' => true, 'title' => 'ID', 'width' => 80, 'fixed' => 'left'])
            ->addRow(['field' => 'code', 'title' => '会员编号', 'width' => 150, 'fixed' => 'left'])
            ->addRow(['field' => 'mobile', 'title' => '手机号', 'width' => 120, 'fixed' => 'left'])
            ->addRow(['field' => 'account', 'title' => '用户名', 'width' => 150])
            ->addRow(['field' => 'nickname', 'title' => '会员昵称']);

        if ($active == 2) {
            $tableFront
                ->addRow(['field' => 'level_id', 'templet' => '<span>{{d.level?d.level.title:"无"}}</span>', 'title' => '会员等级'])
            ;
        }

        if (isset($extra_map['real_status']) && $extra_map['real_status'] == 1) {
            $tableFront->addRow(['field' => 'real_name', 'title' => '真实姓名', 'width' => 150])
                ->addRow(['field' => 'idcard', 'title' => '身份证号', 'width' => 200])
                ->addRow(['field' => 'real_time', 'title' => '认证时间', 'width' => 160]);
        } else {
            $tableFront->addRow(['field' => 'parent_code', 'title' => '推荐人', 'width' => 150])
                ->addRow(['field' => 'child_count', 'title' => '推荐人数', 'width' => 100])
                ;
            $assets = Assets::getFields(3);
            foreach ($assets as $k => $v) {
                if (in_array($k, ['currency', 'bonus'])) {
                    $tableFront->addRow(['field' => $k, 'templet' => '<span>{{d.assets.' . $k . '}}</span>', 'title' => $v, 'width' => 150]);
                }
            }
        }

        if ($active == 2) {
            $tableFront->addRow(['field' => 'active_time', 'title' => '激活时间', 'width' => 150]);
        }

        $tableFront->addRow(['field' => 'create_time', 'title' => '注册时间', 'width' => 150])
            ->addRow(['field' => 'is_lock', 'title' => '锁定登录', 'templet' => '#is_lock', 'width' => 120, 'unresize' => true])
            ->addRow(['fixed' => 'right', 'align' => 'center', 'toolbar' => '#barDemo', 'title' => '操作', 'width' => 150]);

        $RightButtons = [
            'edit' => ['width' => 1000, 'height' => 1000],
        ];
        $RightButtons = $rb ? array_merge($RightButtons, $rb) : $RightButtons;
        $TopButtons = [
            'reset_1' => [
                'title' => '重置登录密码', 'icon' => 'layui-icon-password',
                'url'   => url('user/reset')->build(), 'onclick' => 'buttons.reset($(this),1);'],
            'reset_2' => [
                'title' => '重置支付密码', 'icon' => 'layui-icon-password',
                'url'   => url('user/reset')->build(), 'onclick' => 'buttons.reset($(this),2);'],
            'export'
        ];
        $TopButtons = $tb ? array_merge($tb, $TopButtons) : $TopButtons;

        return TableBuilder::getInstance()
            ->addColumns($tableFront)
            ->addRightButtons($RightButtons)
            ->addTopButtons($TopButtons)
            ->setSearch($this->setSearch($action))
            ->addSwitchTool([['name' => 'contract_bonus_open', 'pk' => 'id', 'text' => '开启|关闭']])
            ->addSwitchTool([['name' => 'is_lock', 'pk' => 'id', 'text' => '锁定|正常']])
            ->addExtraMap($extra_map)
            ->addJsUrl(['user'])
            ->fetch();
    }

    public function setSearch($action = '')
    {
        $front = TableFront::getInstance()
            ->setSearch(['code__nickname__mobile', '会员编号/昵称/手机号', 'input', '', '', '', 'like'])
            ->setSearch(['parent_code', '推荐人编号', 'input', '', '', '', 'like']);
        if($action = 'formal'){
            //$front->setSearch(['level_id', '等级', 'select', \app\common\model\UserLevel::column('title', 'id')]);
        }

        return $front;
    }

    public function add($name = '', $tpl = 'user/add')
    {
        return parent::add($name, $tpl); // TODO: Change the autogenerated stub
    }

    public function edit($name = '', $id = '', $tpl = 'user/edit', $info = '')
    {
        View::assign('level', Level::select());
        View::assign('level_bonus', \app\common\model\UserLevelBonus::select());
        return parent::edit($name, $id, $info); // TODO: Change the autogenerated stub
    }

    public function save($param = [], $model = true): Json
    {
        return parent::save($param, $model); // TODO: Change the autogenerated stub
    }

    public function reset($type)
    {
        try {
            $ids = $this->request->post('ids');
            if ($type == 1) {
                $key = 'password';
                $value = md5('111111');
                $name = '登录密码';
            } else {
                $key = 'pay_password';
                $value = md5('222222');
                $name = '支付密码';
            }
            $this->model::update([$key => $value], ['id' => $ids]);
            $msg = '重置了【' . $name . '】会员标识ID【' . implode(',', $ids) . '】';
            Logs::adds($msg, $this->admin->id, $this->admin->admin_name);
            return json(['code' => 1, 'msg' => '已重置']);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }

    }

    public function relation()
    {
        try {
            if ($this->request->isAjax()) {
                $id = $this->request->param('id');
                $list = $this->model::with(['level'])->where('parent_id', $id)->field('id,code,nickname,mobile,level_id')->select();
                foreach ($list as &$v) {
                    $level = $v->level ? $v->level->title : '暂无';
                    $v['title'] = '编号【' . $v['code'] . '】
                    姓名【' . $v->nickname . '】
                    手机号【' . $v->mobile . '】
                    等级【' . $level . '】
                  ';
                }
                return json(['code' => 1, 'msg' => 'success', 'result' => $list]);
            }
            $keyword = $this->request->param('keyword');
            if ($keyword) {
                $map['code|nickname|mobile'] = $keyword;
            } else {
                $map['code'] = 'admin';
            }
            $first = $this->model::with(['level'])->where($map)->field('id,code,nickname,mobile,level_id')->find();
            if ($first) {
                $level = $first->level ? $first->level->title : '暂无';
                $first['title'] = '编号【' . $first->code . '】
                姓名【' . $first->nickname . '】
                手机号【' . $first->mobile . '】
                等级【' . $level . '】
               ';
            }

            View::assign('first', $first);
            return View::fetch();

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }

    }

    public function login($id)
    {
        try {
            $user = $this->model::find($id);
            if ($user->token) {
                $token = $user->token;
            } else {
                $token = md5(time() . json_encode($user));
                $user->token = $token;
                $user->save();
            }
            cookie('token', $token);
            $description = '登录操作，会员【' . $user->code . '】';
            Logs::adds($description, $this->admin['id'], $this->admin['admin_name']);
            return json(['code' => 1, 'msg' => '登录成功，正在跳转']);
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }

    public function recharge()
    {
        $param = $this->request->param();

        if ($this->request->isAjax()) {
            switch ($param['type']) {
                case "get":
                    $list_rows = [
                        'page' => $this->request->param('page', 1),
                        'list_rows' => $this->request->param('limit', 10)
                    ];
                    $user = $this->model::whereLike('code|mobile|nickname', '%' . $param['val'] . '%')
                        ->field('id,code,mobile,nickname')->where('is_del', 0)->paginate($list_rows);
                    return json(['code' => 0, 'data' => $user->items(), 'count' => $user->total()]);
                case "account":
                    $assets = Assets::where('uid', $param['id'])->value($param['val']);
                    if ($assets) {
                        return json(['code' => 1, 'msg' => '', 'result' => $assets]);
                    } else {
                        return json(['code' => -1, 'msg' => '加载失败']);
                    }

                case "save":

                    try {

                        $this->validate($param, 'Recharge');

                    } catch (ValidateException $e) {
                        return json(['code' => -1, 'msg' => $e->getError()]);
                    }

                    return $this->model::recharge($param, $this->admin);

                default:
                    return json(['code' => -1, 'msg' => '加载失败']);

            }
        }
        //$assets = Assets::getFields(3);
        $assets = [
            'currency'   => '余额',
        ];
        View::assign('assets', $assets);
        return View::fetch();
    }

    public function export()
    {
        $s = $this->setMap($this->request->get('name'));
        $action = $s['param']['name'];
        if('User_formal' == $action){
            $ac = '正式';
            $title = ['id'=>'ID','code'=>'会员编号','nickname'=>'昵称','mobile'=>'手机号','account'=>'账号','level_id'=>'会员等级','active_time'=>'激活时间','create_time'=>'注册时间','is_lock'=>'是否锁定'];

        }elseif('User_real' == $action){
            $ac = '实名';
            $title = ['id'=>'ID','code'=>'会员编号','mobile'=>'手机号','account'=>'账号','level_id'=>'会员等级','nickname'=>'昵称','real_name'=>'真实姓名','idcard'=>'身份证号',
                'real_time'=>'认证时间','create_time'=>'注册时间','is_lock'=>'是否锁定'];
        }else{
            $ac = '普通';
            $title = ['id'=>'ID', 'code'=>'会员编号', 'nickname'=>'昵称', 'mobile'=>'手机号', 'level_id'=>'级别', 'parent_code'=>'推荐', 'create_time'=>'注册时间', 'is_lock'=>'是否锁定'];
        }
        $name = "{$ac}会员列表" . date('Y-m-d H:i:s');
        $s['with'] = $this->hasOne;
        $s['filed'] = array_keys($title);

        //$title = TableFront::getInstance()->getFieldTable($this->request->get('name'));

        if (empty($title)) {
            return json(['code' => -1, 'msg' => '导出失败，请清除缓存后重试！']);
        }

        if (isset($s['param']['is_active']) && $s['param']['is_active'] == 2) {
            if (isset($s['param']['is_service']) && $s['param']['is_service'] == 1) {
                $name = '服务中心列表' . date('Y-m-d H:i:s');
            } else {
                $name = '正式会员列表' . date('Y-m-d H:i:s');
            }
        }
        $assets = Assets::getFields(3);
        $list = $this->model::getSelect($s);

        $agent = ['0'=>'暂无', '1'=>'区代', '2'=>'市代', '3'=>'区代兼市代'];
        $bonus = \app\common\model\UserLevelBonus::column('title', 'id');
        $flag = \app\common\model\UserLevelFlag::column('title', 'id');
        $contract = \app\common\model\ContractLevel::column('title', 'id');

        if('User_formal' == $action){
            $title += [
                'currency'   => '余额',
            ];
        }
        foreach ($list['data'] as &$v) {
            $v->level_id = $v->level ? $v->level->title : '暂无';
            $v->is_lock = $v->is_lock ? '是' : '否';

            if('User_formal' == $action){

            }

            unset($v->level);
            unset($v->assets);
        }

        return json(['code' => 1, 'result' => ['data' => $list['data']->toArray(), 'title' => $title, 'name' => $name]]);
    }

    public function delete($key = 'is_del'): Json
    {
        $id = $this->request->param('id');
        $info = UserModel::where(['id' => $id])->find();
        $count = UserModel::where(['parent_id' => $id])->count('id');
        if ($info->breed_id == 0 && $count == 0) {
            $info->$key = 1;
            $info->save();
            Logs::adds('删除会员，ID【' . $id . '】', $this->admin['id'], $this->admin['admin_name']);
        } else {
            return json(['code' => -1, 'msg' => '禁止删除']);
        }

        return json(['code' => 1, 'msg' => '操作成功']);
    }

    public function getArea($id, $level = 0)
    {
        return Area::getArea($id ?: 100000, $level);
    }

    public function getList($takeOver = true): Json
    {
        return parent::getList($takeOver); // TODO: Change the autogenerated stub
    }

    //商城代理
    public function agentMall(): string
    {
        return $this->setAgentTable('agent_mall');
    }

    public function getAgentMallList(): Json
    {
        return json(UserModel::getAgentList($param = $this->request->param(), 'mall'));
    }

    //合约代理
    public function agentContract(): string
    {
        return $this->setAgentTable('agent_contract');
    }

    public function getAgentContractList(): Json
    {
        return json(UserModel::getAgentList($param = $this->request->param(), 'contract'));
    }

    public function setAgentTable($view = 'agent_mall')
    {
        //构建table
        $tableFront = TableFront::getInstance()
            ->addRow(['type' => 'checkbox', 'fixed' => 'left', 'title' => '全选'])
            ->addRow(['field' => 'id', 'sort' => true, 'title' => 'ID', 'width' => 80])
            ->addRow(['field' => 'code', 'title' => '会员编号', 'width' => 150])
            ->addRow(['field' => 'mobile', 'title' => '手机号', 'width' => 120])
            ->addRow(['field' => 'nickname', 'title' => '会员昵称'])
            ->addRow(['field' => 'level', 'title' => '代理级别'])
            ->addRow(['field' => 'city', 'title' => '代理城市'])
            ->addRow(['field' => 'district', 'title' => '代理区县'])
            ->addRow(['fixed' => 'right', 'align' => 'center', 'toolbar' => '#barDemo', 'title' => '操作', 'width' => 150]);

        return TableBuilder::getInstance()
            ->addColumns($tableFront)
            ->setSearch($this->setAgentSearch())
            ->fetch($view);
    }

    public function setAgentSearch(): TableFront
    {
        return TableFront::getInstance(false)
            ->setSearch(['user', '会员编号/昵称/手机号', 'input', '', '\app\common\model\User', 'code|nickname|mobile,id'])
            ->setSearch(['area', '城市/区县', 'input']);
    }
}
